package rush.rushcampus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import rush.rushcampus.common.BaseContext;
import rush.rushcampus.dto.CommmentDto;
import rush.rushcampus.entity.Comment;
import rush.rushcampus.entity.User;
import rush.rushcampus.mapper.CommentMapper;
import rush.rushcampus.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import rush.rushcampus.dto.CommentPageDto;
import rush.rushcampus.vo.ArticleCommentVo;
import rush.rushcampus.vo.CommentVo;
import rush.rushcampus.vo.UserPartInfoVo;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rush
 * @since 2024-06-11
 */
@Slf4j
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserServiceImpl userService;

    @Override
    public Long countComment(Long id , Integer type) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", id);
        queryWrapper.eq("comment_belongs", type);
        Long count = Long.valueOf(this.count(queryWrapper));
        return count;
    }

    @Override
    public void addComment(CommmentDto commmentDto) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commmentDto, comment);
        comment.setUserId(BaseContext.getCurrenId());
        comment.setAddTime(LocalDateTime.now());
        //不做处理，直接插入
        comment.setAddTime(LocalDateTime.now());

        commentMapper.insert(comment);
    }

    @Override
    public List<CommentVo> listComment(CommentPageDto commentPageDto) {
        Integer StartPage =  (commentPageDto.getPage()-1) * commentPageDto.getSize();
        Integer EndPage = (commentPageDto.getPage()) * commentPageDto.getSize();
        List<CommentVo> CommmentVolist  =  commentMapper.getCommentList(commentPageDto.getArticleId(), commentPageDto.getIsPrivate(),StartPage,EndPage);
        CommmentVolist.forEach(commentVo -> {
            commentVo.setChildCommentCount(commentVo.getChildComment().size());
        });
        return CommmentVolist;
    }



//    @Override
//    public List<ArticleCommentVo> listComment(Long parentId, Integer isPrivate, Integer pageNum, Integer pageSize) {
//        Integer StartPage = (pageNum-1) * pageSize ;
//        Integer EndPage = (pageNum) * pageSize;
//        //查询子评论(自定义sql语句)
////        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
////        queryWrapper.eq("parent_comment", parentId);
////        queryWrapper.eq("is_private", isPrivate);
////        queryWrapper.orderByDesc("add_time");
////        queryWrapper.last("limit " + StartPage + "," + EndPage);
////        List<Comment> commentList = commentMapper.selectList(queryWrapper);
//        List<ArticleCommentVo> commentList = commentMapper.listComment(parentId, isPrivate,StartPage,EndPage);
//        return commentList;
//    }
    @Transactional
    @Override
    public void removeComment(Long articleId) {

        Comment comment = this.getById(articleId);
        if (comment.getParentComment() == null){
            deleteCommentAndChildren(articleId);
        }else {
            deleteCommentAndChildren(comment.getParentComment());
        }

    }

    @Override
    public List<ArticleCommentVo> listArticleComment(Long articleId , Integer commentBelongs) {
        // 查询父级评论 (parent_comment 为 null 的评论)
        List<Comment> parentComments = commentMapper.selectList(
                new QueryWrapper<Comment>()
                        .eq("article_id", articleId)
                        .eq("comment_belongs", commentBelongs)
                        .isNull("parent_comment")
        );

        // 封装成 ArticleCommentVo
        List<ArticleCommentVo> articleCommentVoList = parentComments.stream()
                .map(this::convertToArticleCommentVo)
                .collect(Collectors.toList());

        return articleCommentVoList;
    }

    /**
     * 将 Comment 转换为 ArticleCommentVo，并递归查询子评论
     */
    private ArticleCommentVo convertToArticleCommentVo(Comment comment) {
        ArticleCommentVo articleCommentVo = new ArticleCommentVo();
        // 设置评论的基本信息
        articleCommentVo.setContent(comment.getContent());
        articleCommentVo.setCreateTime(comment.getAddTime());
        articleCommentVo.setIsPrivate(comment.getIsPrivate());
        // 可根据 user_id 查询用户信息
        articleCommentVo.setUserPartInfoVo(getUserPartInfoVoById(comment.getUserId()));

        // 递归查询子评论
        List<Comment> childComments = commentMapper.selectList(
                new QueryWrapper<Comment>()
                        .eq("parent_comment", comment.getId().toString())
        );

        // 如果有子评论，则递归封装子评论列表
        if (!childComments.isEmpty()) {
            List<ArticleCommentVo> childCommentVos = childComments.stream()
                    .map(this::convertToArticleCommentVo)
                    .collect(Collectors.toList());
            articleCommentVo.setChildCommentList(childCommentVos);
        }

        return articleCommentVo;
    }

    /**
     * 根据 userId 查询用户信息
     */
    private UserPartInfoVo getUserPartInfoVoById(Long userId) {
        // 模拟用户信息查询，实际需要根据 userId 查询用户表
        User user = userService.getById(userId);
        UserPartInfoVo userPartInfoVo = new UserPartInfoVo();
        userPartInfoVo.setCreateUserName(user.getUsername());
        userPartInfoVo.setCreateUserAvatar(user.getAvatar());
        userPartInfoVo.setCreateUserSex(user.getGender());
        return userPartInfoVo;
    }

    @Transactional
    public void deleteCommentAndChildren(Long commentId , Integer commentType ) {
        // Step 1: 获取符合 class_comment 的评论列表
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_belongs", commentId);
        queryWrapper.eq("comment_type", commentType);
        List<Comment> commentList = this.list(queryWrapper);

        // Step 2: 处理每条评论
        for (Comment comment : commentList) {
            if (comment.getParentComment() == null) {
                // 直接删除 parent_comment 为 null 的评论（根评论）
                deleteCommentAndChildren(comment.getId());
            } else {
                // Step 3: 处理子评论的情况，递归删除子评论
                deleteCommentAndChildren(comment.getParentComment());
            }
        }

    }

    private void deleteCommentAndChildren(Long commentId) {
        // 删除当前评论
        this.removeById(commentId);

        // 查找是否有子评论
        QueryWrapper<Comment> childQueryWrapper = new QueryWrapper<>();
        childQueryWrapper.eq("parent_comment", commentId);
        List<Comment> childComments = this.list(childQueryWrapper);

        // 递归删除子评论
        for (Comment childComment : childComments) {
            deleteCommentAndChildren(childComment.getId());
        }
    }
}
